//
//  RAPAccountViewModel.swift
//  COPYCAT-Weibo
//
//  Created by 闫萌 on 12/30/15.
//  Copyright © 2015 RendezvousAuParadis. All rights reserved.
//

import UIKit



class RAPAccountViewModel: NSObject {
    /*
    单例属性
    */
    static let sharedViewModel : RAPAccountViewModel = {
        let viewModel = RAPAccountViewModel()
        return viewModel
        }()
    
    private var accountModel: RAPAccountModel?
    
    
    func beginOauthValidationByCode(code: String, completion:(isSuccess: Bool)->()) {
        /*
        请求accesss token
        */
        RAPAFNHTTPRequestTool.sharedTool.fetchAccessTokenByCode(code) { (responseObject, error) -> () in
            if error != nil { // 如果发生错误，则表示请求失败
                completion(isSuccess: false)
                return
            }
            
            // 字典转换为模型
            let model = RAPAccountModel(dict: responseObject as! [String: NSObject])
            
            /*
            请求 用户信息
            */
            RAPAFNHTTPRequestTool.sharedTool.fetchUserInfo(model, finished: { (responseObject, error) -> () in
                if error != nil {
                    completion(isSuccess: false)
                    return
                }
                
                guard let dict = responseObject as? [String: NSObject]  else {
                    return
                }
                model.screen_name = dict["screen_name"] as? String
                model.avatar_large = dict["avatar_large"] as? String
                // 拿到模型
                self.accountModel = model
    
                // 将账户信息写入沙盒
                self.wirteAccountInfo()
                
                // 成功回调
                completion(isSuccess: true)
            })

        }
    }

    
    func newViersionCheck() -> Bool {
        // 从info.plist中读取
        let newVersion = NSBundle.mainBundle().infoDictionary!["CFBundleVersion"] as! String
        
        /*
        如果当前不能从userdefault中读取到之前的版本信息，则肯定是新版本
        */
        if let current = NSUserDefaults.standardUserDefaults().objectForKey(kRAPCurrentVersion) {
            // 如果之前的版本信息小于当前版本信息，则是新版本，否则，不是
            return current.compare(newVersion) == .OrderedAscending ? true : false
        }
        
        return true
    }
    
    /**
    读取token
    */
    func accessToken() -> String? {

        return readAccountInfo()?.access_token
    }
    
    func loginCheck() -> Bool {
        /*
        如果沙盒保存着账户信息，且账户信息中含有access token，且token尚未过期
        */
        if accessToken() != nil && !isTokenExpired() {
            return true
        }
        
        // 如果读取到就是登录
        return false
    }
    
    func isTokenExpired() -> Bool {
        let now = NSDate()
        let then = readAccountInfo()?.expireDate
        
        /*
        如果当前时间小于过期时间，就没有过期，否则过期
        */
        return now.compare(then!) == NSComparisonResult.OrderedAscending ? false : true
    }
    
    
    override init() {
        super.init()
        accountModel = readAccountInfo()
    }
    
}

// MARK: - Archive&Unarchive
extension RAPAccountViewModel {
    /**
    将账户信息写入沙盒
    */
    func wirteAccountInfo() {
        NSKeyedArchiver.archiveRootObject(accountModel!, toFile: getFilePath())
    }
    

    
    /**
    从沙盒中读取账户信息，注意，不一定能读取到
    */
    func readAccountInfo() -> RAPAccountModel? {
        
        let model = NSKeyedUnarchiver.unarchiveObjectWithFile(getFilePath()) as? RAPAccountModel

        return model
    }
    
    private func getFilePath() -> String {
        let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).first
        return (path! as NSString).stringByAppendingPathComponent("accountInfo")
    }
}
